package util

import (
	"time"
)

const timeFormat = "2006-01-02 15:04:05"
const dateFormat = "2006-01-02"

func NowTimestamp() int64 {
	return time.Now().UnixMilli()
}

func TimeStamp2Time(tp int64) time.Time {
	return time.UnixMilli(tp)
}

func Time2TomeStamp(t time.Time) int64 {
	return t.UnixMilli()
}

func Time2String(t time.Time) string {
	return t.Format(timeFormat)
}

func Time2StringWithFormat(t time.Time, format string) string {
	return t.Format(format)
}

func Time2DateString(t time.Time) string {
	return t.Format(dateFormat)
}

func String2Time(s string) (time.Time, error) {
	loc, _ := time.LoadLocation("Local")
	return time.ParseInLocation(timeFormat, s, loc)
}

// AddAtLeastOneDay 如果离第二天target小时满24小时,则加到第二天的target小时,如果不够24小时,加到后天的target小时
func AddAtLeastOneDay(now int64, day, target int) int64 {
	t := time.UnixMilli(now)
	if t.Hour() >= target {
		day++
	}
	t = time.Date(t.Year(), t.Month(), t.Day()+day, target, 0, 0, 0, time.Local)
	return t.UnixMilli()
}

func AddDay(now int64, day, targetHour int) int64 {
	t := time.UnixMilli(now)
	//filling := 0
	t = time.Date(t.Year(), t.Month(), t.Day()+day, targetHour, 0, 0, 0, time.Local)
	return t.UnixMilli()
}
func AddMinute(now int64, minute int) int64 {
	t := time.UnixMilli(now)
	//filling := 0
	t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute()+minute, t.Second(), 0, time.Local)
	return t.UnixMilli()
}

func DayGap(src, target time.Time) float64 {
	dst := src.Sub(target)
	return dst.Hours() / 24
}

func MinuteGap(src, target time.Time) float64 {
	dst := src.Sub(target)
	return dst.Minutes()
}

// 获取周一的日期
func GetMondayOfWeek(t time.Time) (dayStr string) {
	dayObj := GetZeroTime(t)
	if t.Weekday() == time.Monday {
		//修改hour、min、sec = 0后格式化
		dayStr = dayObj.Format(dateFormat)
	} else {
		offset := int(time.Monday - t.Weekday())
		if offset > 0 {
			offset = -6
		}
		dayStr = dayObj.AddDate(0, 0, offset).Format(dateFormat)
	}
	return
}

// 获取某一天的0点时间
func GetZeroTime(t time.Time) time.Time {
	return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
